package com.xyzwps.server.paimon.jackson

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.KeyDeserializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.xyzwps.server.paimon.value.Phone


class PhoneJacksonSerializer : StdSerializer<Phone>(Phone::class.java) {
    override fun serialize(value: Phone?, gen: JsonGenerator, provider: SerializerProvider) {
        if (value == null) {
            gen.writeNull()
        } else {
            gen.writeString(value.value)
        }
    }
}

class PhoneJacksonDeserializer : StdDeserializer<Phone>(Phone::class.java) {
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Phone? =
        when (val token = p.currentToken) {
            JsonToken.VALUE_NULL -> null
            JsonToken.VALUE_STRING -> Phone(p.text)
            else -> throw JsonMappingException.from(p, "Unexpected token $token")
        }
}

class PhoneJacksonKeyDeserializer : KeyDeserializer() {
    override fun deserializeKey(key: String?, ctxt: DeserializationContext): Any? =
        if (key == null) null else Phone(key)
}

fun SimpleModule.registerPhone() {
    addSerializer(Phone::class.java, PhoneJacksonSerializer())
    addDeserializer(Phone::class.java, PhoneJacksonDeserializer())
    addKeySerializer(Phone::class.java, PhoneJacksonSerializer())
    addKeyDeserializer(Phone::class.java, PhoneJacksonKeyDeserializer())
}